// pages/cart/index.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart: [],
    address: {},
    checked: true,
    totalmoney: 0,
    goodsnum: 0,


  },


  onShow() {

    this.getCartList()
    this.getAddress()

  },
  getCartList() {
    let totalmoney = 0;
    let goodsnum = 0;

    const cart = wx.getStorageSync("cart") || [];

    const checked = cart.every(e => e.checked === true)

    cart.forEach(e => {
      if (e.checked === true) {
        totalmoney += e.goods_price * e.num,
          goodsnum += e.num
      }
    })




    this.setData({
      cart,
      checked,
      totalmoney,
      goodsnum



    })
  },
  getAddress() {
    const address = wx.getStorageSync("address");
    this.setData({
      address
    })
  },
  handelGetAddress() {
    wx.chooseAddress({
      success: (address) => {
        wx.setStorageSync("address", address);


      },
    });
    this.getAddress()

  },
  handleAllcheck() {

    const checked = !this.data.checked
    const cart1 = JSON.parse(JSON.stringify(this.data.cart))
    cart1.forEach(e => e.checked = checked);
    wx.setStorageSync("cart", cart1);
    const cart = wx.getStorageSync("cart");
    this.setData({
      cart,
      checked
    })

    this.getCartList()


  },
  handlegoodchecked(e) {
    const { index } = e.currentTarget.dataset
    const cart1 = JSON.parse(JSON.stringify(this.data.cart))
    cart1[index].checked = !cart1[index].checked
    wx.setStorageSync("cart", cart1);
    const cart = wx.getStorageSync("cart");
    this.setData({
      cart
    })
    this.getCartList()
  },
  handlereduce(e) {
    const { index } = e.currentTarget.dataset
    const cart1 = JSON.parse(JSON.stringify(this.data.cart))
    cart1[index].num--
    if (cart1[index].num >= 0) {
      wx.setStorageSync("cart", cart1);
      const cart = wx.getStorageSync("cart");

      this.getCartList()
    } else {
      wx.showModal({
        title: '提示',
        content: '您确定要删除该商品吗',

        success: (result) => {
          if (result.confirm) {
            cart1.splice(index, 1)
            wx.setStorageSync("cart", cart1);
            this.getCartList()
          }
        },

      });


    }



  },
  handleadd(e) {
    const { index } = e.currentTarget.dataset
    const cart1 = JSON.parse(JSON.stringify(this.data.cart))
    cart1[index].num++

    wx.setStorageSync("cart", cart1);
    const cart = wx.getStorageSync("cart");
    this.setData({
      cart
    })
    this.getCartList()
  },
  handlePay() {
    const cart1 = JSON.parse(JSON.stringify(this.data.cart))
    const cart2 = cart1.filter(e => e.checked)
    if (!this.data.address.userName) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',

      });

    } else if (cart2.length === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',

      });
    } else {
      wx.navigateTo({
        url: '/pages/pay/index',

      });
    }


  }




})